# -*- coding: utf-8 -*-

'''
服务订单分派任务函数
'''
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList
import pandas as pd
import uuid
import datetime
import re
import random
import string
import hashlib
from enum import Enum
from ...pao_python.pao.service.security.security_service import RoleService
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...service.common import insert_data, find_data, update_data, delete_data, get_condition, get_info, get_cur_time, get_current_user_id
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.mongo_bill_service import MongoBillFilter
from ...service.buss_mis.service_operation import ServiceOperationService
from ...service.buss_mis.task_manage import TaskManageService, TaskState, UrgentLevel

# 剩余次数


class RemainTimes(Enum):
    '''剩余次数'''
    Yes = '有'
    No = '无'


class ServiceOrderTaskService(MongoService):
    ''' 服务订单分派 '''

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        DataProcess.__init__(self, db_addr, db_port, db_name, db_user, db_pwd)
        # self.db_name = db_name
        self.inital_password = inital_password
        self.session = session
        self.role_service = RoleService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)
        self.bill_manage_server = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)
        self.service_operation_func = ServiceOperationService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    def get_services_item_category_list(self):
        '''获取服务项目类别列表
        '''
        _filter = MongoBillFilter()
        _filter.match_bill()\
               .project({'_id': 0})
        res = self.query(_filter, 'PT_Services_Item_Category')
        return res

    def get_service_order_task_list(self, order_ids, condition, page, count):
        '''获取服务项目类别列表

        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        '''
        if 'order_date' in list(condition.keys()):
            condition['start_date'] = condition['order_date'][0]
            condition['end_date'] = condition['order_date'][1]
        keys = ['id', 'service_item_category', 'start_date', 'end_date']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill(C('organization_id').inner(order_ids))\
            .match_bill((C('bill_status') == Status.bill_valid.value)
                        & (C('create_date') >= as_date(values['start_date']))
                        & (C('create_date') <= as_date(values['end_date']))
                        & (C('origin_product') != None)
                        & (C('id') == values['id']))\
            .lookup_bill('PT_User', 'purchaser_id', 'id', 'purchaser_info')\
            .unwind('purchaser_info', True)\
            .lookup('PT_User', 'service_provider_id', 'id', 'serviceProvider')\
            .add_fields({
                # 'count': '$detail.count',
                'product_name': '$origin_product.product_name',
                'purchaser_name': '$purchaser_info.name',
                'purchaser_address': '$purchaser_info.personnel_info.address',
                'service_item_category_name': '$services_item_cateogry.name',
                'service_provider_name': '$serviceProvider.name',
                # 'all_times': '$detail.all_times',
            })\
            .project({'_id': 0,
                      'purchaser_info': 0,
                      'serviceProvider': 0,
                      'services_item_cateogry._id': 0})
        res = self.page_query(
            _filter, 'PT_Service_Order', page, count)

        return res

        newArray = []

        for item in res['result']:

            # 补全总次数
            if 'all_times' not in item:
                item['all_times'] = 0

            # 查询服务记录数量
            _filter_record = MongoBillFilter()
            _filter_record.match_bill((C('bill_status') == Status.bill_valid.value)
                                      & (C('servicer_id') == item['service_provider_id'])
                                      & (C('service_product_id') == item['detail']['product_id'])
                                      & (C('order_id') == item['id']))
            _filter_record.project({'_id': 0})
            record_res = self.query(_filter_record, "PT_Service_Record")

            # 拼接一个Id
            item['pinId'] = item['id'] + '-' + \
                item['detail']['product_id']
            # 剩余次数
            remaining_times = int(item['all_times']) - len(record_res)
            # 排除小于0的情况
            item['remaining_times'] = remaining_times if(
                remaining_times > 0) else 0

            # 由于重复ID会造成前端数据紊乱，这里需要暂存之后再赋予随机生成
            item['origin_id'] = item['id']
            item['id'] = ''.join(random.sample(
                string.ascii_letters + string.digits, 32))

            newArray.append(item)

        res['result'] = newArray
        res['total'] = len(newArray)

        return res

    def update_service_order_task(self, datas):
        '''# 新增/修改服务订单任务分派'''
        res = 'Fail'

        # 给服务记录接口的数据
        record_data = datas['record_data']
        # 给任务接口的数据
        task_data = datas['task_data']

        # 判断是否已经存在，如果存在，就删除重建
        _filter_record = MongoBillFilter()
        _filter_record.match_bill((C('order_id') == record_data['order_id'])
                                  & (C('servicer_id') == record_data['other']['servicer_id'])
                                  & (C('service_product_id') == record_data['product_id']))\
            .lookup_bill('PT_Task', 'id', 'task_object_id', 'task')\
            .project({'_id': 0, 'task._id': 0})
        record_res = self.query(_filter_record, 'PT_Service_Record')

        # 如果有
        if len(record_res):
            if record_res[0]['status'] != '未服务':
                return '该任务已经进行中'

            # 开始删除记录和任务
            self.bill_manage_server.add_bill(
                OperationType.delete.value, TypeId.serviceRecord.value, [{'id': record_res[0]['id']}, {'id': record_res[0]['task'][0]['id']}], ['PT_Service_Record', 'PT_Task'])

        # 获取任务类别，要有一个为系统的，没有就创建一个
        _filter_task_type = MongoBillFilter()
        _filter_task_type.match_bill(C('name') == '服务分派')\
            .project({'_id': 0})
        task_type_res = self.query(_filter_task_type, 'PT_Task_Type')

        if len(task_type_res) > 0:
            task_type_id = task_type_res[0]['id']
        else:
            task_type_data = get_info({
                'name': '服务分派',
                'remark': '服务订单分派',
            }, self.session)
            task_type_id = task_type_data['id']
            bill_id = self.bill_manage_server.add_bill(
                OperationType.add.value, TypeId.taskType.value, task_type_data, 'PT_Task_Type')

        # 当前登录人
        now_user_id = get_current_user_id(self.session)

        # 查找订单的产品
        _filter_serviceOrder = MongoBillFilter()
        _filter_serviceOrder.match_bill((C('id') == record_data['order_id'])
                                        & (C('detail') != None))\
            .unwind('detail', True)\
            .project({'_id': 0})
        res_serviceOrder = self.query(_filter_serviceOrder, 'PT_Service_Order')
        # 有数据 and 有产品
        if len(res_serviceOrder) > 0:
            # 生成所有服务记录
            for item in res_serviceOrder:

                all_times = 1
                count = 1

                # 判断服务次数
                if 'all_times' in item['detail'] and item['detail']['all_times'] != None:
                    if type(item['detail']['all_times']) != int:
                        all_times = int(item['detail']['all_times'])
                    else:
                        all_times = item['detail']['all_times']
                # 判断数量
                if 'count' in item['detail'] and item['detail']['count'] != None:
                    if type(item['detail']['count']) != int:
                        all_times = int(item['detail']['count'])
                    else:
                        all_times = item['detail']['count']

                # 总的服务次数，根据服务次数*数量生成服务记录
                service_all_times = all_times * count

                for x in range(0, int(service_all_times)):
                    # 置空操作
                    # 任务数据
                    temp_task_data = dict(**task_data)
                    # 任务名称
                    temp_task_data['task_name'] = item['detail']['product_name']
                    temp_task_data['task_content'] = item['detail']['product_name']
                    # 任务状态为待处理
                    temp_task_data['task_state'] = TaskState.To_be_receive.value
                    # 任务类型
                    temp_task_data['task_type'] = task_type_id
                    # 任务紧急程度
                    temp_task_data['task_urgent'] = UrgentLevel.Normal.value
                    # 创建人为当前登录的ID
                    temp_task_data['task_creator'] = now_user_id
                    # 购买者ID
                    temp_task_data['purchaser_id'] = res_serviceOrder[0]['purchaser_id']

                    # 补全服务记录接口需要的service_option
                    record_data['other']['service_option'] = item['detail']['service_option']
                    # 给一个未回访的字段
                    record_data['other']['is_huifang'] = '否'
                    # 首先调用接口
                    service_record = self.service_operation_func.add_service_record(
                        record_data['order_id'], item['detail']['product_id'], False, record_data['other'])

                    # 先预给id
                    service_record = get_info(service_record, self.session)
                    # 如果是平台下单则加buy_type为平台下单
                    service_record['buy_type'] = item['buy_type']
                    # 存服务订单记录的id
                    temp_task_data['task_object_id'] = service_record['id']

                    # 同时插入数据
                    bill_id = self.bill_manage_server.add_bill(
                        OperationType.add.value, TypeId.serviceTask.value, [service_record, temp_task_data], ['PT_Service_Record', 'PT_Task'])
                    if bill_id:
                        res = 'Success'
            if bill_id:
                self.bill_manage_server.add_bill(
                    OperationType.update.value, TypeId.serviceOrder.value, {'id': record_data['order_id'], 'order_state': '已分派', 'status': '已分派'}, 'PT_Service_Order')
        return res
